package com.ganbo.pattern.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 容器式单利模式
 * Created by gan on 2020/6/8 22:40.
 */
public class ContainerSingleton {

    private static Map<String, Object> ioc = new ConcurrentHashMap();

    private ContainerSingleton() {

    }

    public static Object getInstance(String beanName) {
        Object instance = ioc.get(beanName);
        if (instance != null) {
            return ioc.get(beanName);
        } else {
            synchronized (ContainerSingleton.class) {
                if (getInstance(beanName) == null) {
                    try {
                        instance = Class.forName(beanName).newInstance();
                        ioc.put(beanName, instance);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return instance;
            }
        }
    }
}
